from flask import Flask, request, jsonify, send_from_directory
from network_client import NetworkClient
import threading
import time
import logging

app = Flask(__name__)
network_client = NetworkClient()

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('WebServer')

@app.route('/')
def index():
    return send_from_directory('static', 'index.html')

@app.route('/configure', methods=['POST'])
def configure():
    data = request.get_json()
    logger.debug(f"收到配置请求: {data}")
    
    if not data or 'protocol' not in data or 'ip' not in data or 'port' not in data:
        logger.warning("配置请求缺少必要参数")
        return jsonify({
            'success': False,
            'message': '缺少必要参数(protocol/ip/port)'
        })
    
    try:
        if network_client.configure(data['protocol'], data['ip'], data['port']):
            return jsonify({'success': True})
        else:
            return jsonify({
                'success': False,
                'message': '配置验证失败'
            })
    except Exception as e:
        logger.error(f"配置出错: {str(e)}")
        return jsonify({
            'success': False,
            'message': str(e)
        })

@app.route('/status')
def status():
    status = network_client.get_status()
    status.update({
        'timestamp': time.time(),
        'hostname': socket.gethostname(),
        'local_ip': socket.gethostbyname(socket.gethostname())
    })
    return jsonify(status)

@app.route('/disconnect', methods=['POST'])
def disconnect():
    try:
        network_client.disconnect()
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({
            'success': False,
            'message': str(e)
        })

@app.route('/send', methods=['POST'])
def send_data():
    data = request.get_json()
    if not data or 'message' not in data:
        return jsonify({
            'success': False,
            'message': '缺少消息内容'
        })
    
    if network_client.send_data(data['message']):
        return jsonify({'success': True})
    else:
        return jsonify({
            'success': False,
            'message': '发送失败，请检查连接状态'
        })

def run_flask():
    app.run(
        host='0.0.0.0',
        port=8080,
        threaded=True,
        use_reloader=False
    )

if __name__ == '__main__':
    import socket
    
    # 启动Flask服务
    flask_thread = threading.Thread(
        target=run_flask,
        name="FlaskThread",
        daemon=True
    )
    flask_thread.start()
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        network_client.disconnect()
        logger.info("程序退出")